<template>
  <div class="image">
    <BlackModal :open="open" @close="open = false" @wheel="changeSliderDefaultValue">
      <div class="image-black">
        <div class="image-black-img">
          <img :src="src" alt="" :width="imgSize.width" :height="imgSize.height" :style="`transform: scale(${scaleRate})`" />
        </div>
        <div class="image-black-footer">
          <Slider :default="defaultValue" :range="range" @change="getCurrentRange"></Slider>
        </div>
      </div>
    </BlackModal>
    <div class="image-prew">
      <div v-if="src" class="image-prew-src" ref="imgShowBox" @click="previewImage">
        <img :src="src" alt="预览图片" />
        <div class="image-prew-black">
          <span>预览</span>
          <i class="iconfont iconyanjing image-prew-black-preview"></i>
        </div>
      </div>
      <div v-if="!src" class="image-prew-fail" @click="reloadImage">
        <i class="iconfont icontuku"></i>
        <p>图片加载失败</p>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { defineProps, ref, defineEmits, watch } from 'vue'
import BlackModal from '../BlackModal/BlackModal.vue'
import Slider from '../Slider/index.vue'
type ImagePropsType = {
  src: string
}

const props = defineProps<ImagePropsType>()

const emit = defineEmits(['reload'])

// 图片尺寸
const imgSize = ref({
  width: 0,
  height: 0
})
const defaultValue = ref(1)
const range = ref<[number, number]>([1, 10])
const scaleRate = ref<number>(1)

watch(
  () => props.src,
  (newValue) => {
    const img = new Image()
    img.src = newValue
    img.onload = () => {
      const { width, height } = img

      const max = {
        width: 500,
        height: 300
      }
      const rate = width / height
      if (rate > 2) {
        imgSize.value = {
          width: max.width,
          height: height / (width / max.width)
        }
      } else {
        imgSize.value = {
          width: width / (height / max.height),
          height: max.height
        }
      }
    }
  },
  { deep: true, immediate: true }
)

const open = ref<boolean>(false)
const imgShowBox = ref<HTMLDivElement | null>(null)

// 预览图片
const previewImage = () => {
  open.value = true
}

const getCurrentRange = (location: number) => {
  scaleRate.value = 1 + location / 5
}

// 修改当前滑动条的默认值
const changeSliderDefaultValue = (e: WheelEvent) => {
  if (e.deltaY > 1) {
    defaultValue.value += 1
  } else if (e.deltaY < -1) {
    defaultValue.value -= 1
  }
}

// 重新加载
const reloadImage = () => {
  emit('reload')
}
</script>

<style lang="scss" scoped>
@import './style.scss';
</style>
